package com.example.config;

import com.example.base.Redis.FastJsonRedisSerializer;
import com.example.base.Redis.RedisAccessManager;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.lang.reflect.Method;
import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
    /**
     * 自定义生成key的规则
     */
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                //格式化缓存key字符串
                StringBuilder sb = new StringBuilder();
                //追加类名
                sb.append(method.getDeclaringClass().getSimpleName());
                sb.append(":");
                sb.append(method.getName());
                sb.append(":");
                sb.append( method.getReturnType().getSimpleName());
                sb.append(":");
                //遍历参数并且追加
                for (Object obj : objects) {
                    sb.append(obj.toString());
                }
                System.out.println("调用Redis缓存Key : " + sb.toString());
                return sb.toString();
            }
        };
    }

    /**
     * 采用RedisCacheManager作为缓存管理器
     * @param
     */
    @Bean
    /*  redis-cache configuration */
    public CacheManager cacheManager(RedisConnectionFactory factory) {
           // 配置序列化（解决乱码的问题）
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 7 天缓存过期
                .entryTtl(Duration.ofDays(7))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer( new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new FastJsonRedisSerializer(Object.class)))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }

    @Bean
    public RedisAccessManager redisManager(){
        RedisAccessManager redisAccessManager = new RedisAccessManager();
         return redisAccessManager;
    }
    @Bean
    public RedisTemplate<String, Object> redisTemplateObject(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂
        redisTemplate.setConnectionFactory(factory);
        // 设置key是String序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置value是json对象序列化
        FastJsonRedisSerializer fastSerializer =new FastJsonRedisSerializer(Object.class);
        redisTemplate.setValueSerializer(fastSerializer);//new RedisObjectSerializer()
        // 设置hash key是String序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // 设置hash value是jdk序列化
        redisTemplate.setHashValueSerializer(fastSerializer);
        // 设置默认策略
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }





}